package com.commerceerp.system.service;

import com.commerceerp.system.entity.ImageVo;
import com.commerceerp.system.mapper.ImageMapper;
import com.commerceerp.system.pay.AliPayCode;
import com.commerceerp.system.pay.WxPayCode;
import com.commerceerp.system.util.ApiResult;
import com.commerceerp.system.util.FileUtil;
import com.commerceerp.system.util.RdPage;
import com.commerceerp.system.util.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Administrator on 2018/10/29 0029.
 */
@Service
public class ImageService {

    @Autowired
    private ImageMapper imageMapper;

    //添加图片
    @Transactional
    public ApiResult addFile(MultipartFile file, String userId) {
        if (!file.isEmpty()) {
            long size = file.getSize();
            //已经使用空间
            long useSpace = imageMapper.getUseSpace(userId);
            //用户拥有空间
            long space = 100000000 + imageMapper.getSpace(userId);
            if(space < useSpace + size) {
                return new ApiResult(405, "图片空间不足");
            }
            ImageVo imageVo = new ImageVo();
            imageVo.setUserId(userId);
            String resumeurl = "";

            //重新生成文件名，避免乱码问题
            String filename = file.getOriginalFilename();
            String fName = null;
            if (filename.indexOf(".") >= 0) {
                imageVo.setName(filename.substring(0, filename.lastIndexOf(".")));
                fName = filename.substring(filename.lastIndexOf("."), filename.length());
            }
            String path = String.valueOf(new Random().nextInt(100)).concat((fName));//拼接新文件名
            resumeurl = String.valueOf(new Date().getTime()).concat(path);
            try {
                //上传图片
                FileUtil.addFile(file, "static/img/", resumeurl);
            } catch (Exception e) {
                e.printStackTrace();
                return new ApiResult(405, "上传失败," + e.getMessage());
            }
            imageVo.setUrl("https://www.mind-erp.com/upload/img/" + resumeurl);
            imageVo.setSize(file.getSize());
            imageVo.insert();
            imageMapper.insert(imageVo);
            return new ApiResult(imageVo);

        } else {
            return new ApiResult(405, "上传失败，因为文件是空的.");
        }
    }

    //删除线上文件
    public ApiResult fileDelete(String id,String userId) {
        List<ImageVo> imageVos = imageMapper.get(id.split(","),userId);
        if(imageVos == null || imageVos.size() ==0){
            return new ApiResult(405, "图片不存在");
        }
        for(ImageVo imageVo : imageVos){
            String path = imageVo.getUrl().replace("https://www.mind-erp.com/upload/img/", "");
            FileUtil.delFile("static/img/" + path);
            imageMapper.fileDelete(imageVo.getId());
        }
        return new ApiResult(200, "删除成功");
    }

    //查看图片
    public ApiResult findList(String userId, Integer page, Integer limit) {
        int count =  imageMapper.findListCount(userId);
        if(count > 0){
            return new ApiResult(200,"",imageMapper.findList(userId,(page - 1) * limit,limit),new RdPage(count,page,limit));
        }
        return new ApiResult(405,"没有数据");
    }

    //图片空间
    public ApiResult imgSpace(String userId) {
        //已经使用空间
        long useSpace = imageMapper.getUseSpace(userId);
        //用户拥有空间
        long space = 100000000 + imageMapper.getSpace(userId);
        //剩余空间
        long surplus = space - useSpace;
        //存储的张数
        int count =  imageMapper.findListCount(userId);
        Map data = new HashMap();
        data.put("useSpace",new BigDecimal(useSpace).divide(new BigDecimal(1000000), 2, BigDecimal.ROUND_HALF_UP));
        data.put("space",new BigDecimal(space).divide(new BigDecimal(1000000), 2, BigDecimal.ROUND_HALF_UP));
        data.put("surplus",new BigDecimal(surplus).divide(new BigDecimal(1000000), 2, BigDecimal.ROUND_HALF_UP));
        data.put("count",count);
        return new ApiResult(data);
    }


    //扩容空间
    public ApiResult addSpace(Integer size, int type,String userId) {
        // TODO: 2018/8/23 0023 测试改为0.01
        String vipFees = "0.01";
        String id = StringUtils.getUUID();
        String url = "";
//        if(type == 0){//支付宝
//            ApiResult order = AliPayCode.aliPay(id,vipFees,"增加图片空间"+size+"M");
//            if(order.getCode() == 200){
//                url = (String)order.getData();
//            }else{
//                return order;
//            }
//        }else{//微信
//            try {
//                url = WxPayCode.getWxPayQRCode(StringUtils.getIp(),id,vipFees,"增加图片空间"+size+"M");
//            } catch (Exception e) {
//                e.printStackTrace();
//                return new ApiResult(405,"微信创建订单失败");
//            }
//        }
        //添加记录
        imageMapper.addRecord(id,userId,size * 1000000,type);
        rechargeBack(id);
        return new ApiResult(200,url,"创建订单");
    }

    //支付回调
    @Transactional
    public void rechargeBack(String id) {
        imageMapper.updSpace(id);
        //根据空间id获取空间信息
        Map spaceInfo = imageMapper.getSpaceById(id);
        String userId = (String)spaceInfo.get("userId");
        //已经使用空间
        long useSpace = imageMapper.getUseSpace(userId);
        //用户拥有空间
        long space = 100000000 + imageMapper.getSpace(userId);
        //内存充足
        if(space > useSpace ) {
            //查看废弃的图片
            List<ImageVo> list = imageMapper.findAllList(userId,"1");
            for(ImageVo img : list){
                String path = img.getUrl().replace("https://www.mind-erp.com/upload/img/", "");
                try {
                    FileUtil.move("static/discard/" + path,"static/img/" + path);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                FileUtil.delFile("static/discard/" + path);
                //修改图片状态
                imageMapper.updDelImg(img.getId(),"0");
            }
        }
    }

    public ApiResult getList(String userId, Integer page, Integer limit) {
        //已经使用空间
        long useSpace = imageMapper.getUseSpace(userId);
        //用户拥有空间
        long space = 100000000 + imageMapper.getSpace(userId);
        if(useSpace > space){
            return new ApiResult(405,"您的图片空间不足，请删除多余的图片或扩容图片空间");
        }
        int count =  imageMapper.findListCount(userId);
        if(count > 0){
            return new ApiResult(200,"",imageMapper.findList(userId,(page - 1) * limit,limit),new RdPage(count,page,limit));
        }
        return new ApiResult(405,"没有数据");
    }

    //空间过期，迁移图片
    public void imageSpace() {
        //图片空间过期的用户
        List<String> userIds = imageMapper.getOverDue();
        for(String userId : userIds){
            //查看图片
            List<ImageVo> list = imageMapper.findAllList(userId,"0");
            for(ImageVo img : list){
                String path = img.getUrl().replace("https://www.mind-erp.com/upload/img/", "");
                try {
                    FileUtil.move("static/img/" + path,"static/discard/" + path);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                FileUtil.delFile("static/img/" + path);
                //修改图片状态
                imageMapper.updDelImg(img.getId(),"1");
            }
        }
    }

}
